﻿using HomeWork911.Api.Read.Appliaction.Commond;
using HomeWork911.Api.Read.Dto;
using HomeWork911.Domain;
using HomeWork911.ErrorCode;
using HomeWork911.infrastrunceture;
using MediatR;

namespace HomeWork911.Api.Read.Appliaction.CommondHandler
{
    public class ShowPermissionCommondHandler : IRequestHandler<ShowPermissionCommond, ApiResult<ApiPaging<ShowPermissionDto>>>
    {
        private readonly IBaseIRepository<Permission> permissions;

        public ShowPermissionCommondHandler(IBaseIRepository<Permission> permissions)
        {
            this.permissions = permissions;
        }

        public Task<ApiResult<ApiPaging<ShowPermissionDto>>> Handle(ShowPermissionCommond request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<ShowPermissionDto>> result=new ApiResult<ApiPaging<ShowPermissionDto>>();
            result.Code = ApiEnum.查询成功;
            result.Msg = ApiEnum.查询成功.ToString();
            var list = from a in permissions.GetAll()
                       select new ShowPermissionDto()
                       {
                           PermissionId = a.PermissionId,
                           PermissionName = a.PermissionName,
                           PermissionUrl = a.PermissionUrl,
                           Number = a.Number,
                       };
            var totoCount = list.Count();
            var totoPage = (int)Math.Ceiling(totoCount * 1.0 / request.Pagesize);
            list = list.OrderBy(x => x.Number).Skip((request.Pageindex - 1) * request.Pagesize).Take(request.Pagesize);
            ApiPaging<ShowPermissionDto> paging = new ApiPaging<ShowPermissionDto>();
            paging.totoPage = totoPage;
            paging.totoCount = totoCount;
            paging.data=list.ToList();
            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
